<template>
  <div class="chart">
    <div ref="chart" :style="{ height: height, width: width }" />
  </div>
</template>
<script>
export default {
  name: 'Chart',
  props: {
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      // default: '350px'
      default: '100%',
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartOption: {
      type: Object,
      required: true,
    },
    type: {
      type: String,
      default: 'svg',
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartOption: {
      deep: true,
      handler(newVal) {
        this.setOptions(newVal);
      },
    },
  },
  mounted() {
    this.initChart();
    if (this.autoResize) {
      window.addEventListener('resize', this.resizeHandler);
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.resizeHandler);
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    resizeHandler() {
      this.chart.resize();
    },
    initChart() {
      this.chart = this.$echarts.init(this.$refs.chart, '', {
        renderer: this.type,
        devicePixelRatio: 2, // 设备像素比 transform: scale(x,y) 缩放时，高分辨率图表不会模糊
      });
      this.chart.setOption(this.chartOption);
      this.chart.on('click', this.handleClick);
      this.chart.off('legendselectchanged').on('legendselectchanged', this.handleClickSelectChanged);
    },
    handleClick(params) {
      this.$emit('click', params);
    },
    handleClickSelectChanged(params) {
      // 图表不为饼图时，只显示当前点击图例
      if (this.chartOption.series[0].type != 'pie') {
        //点击之后所有被选中的图例数组
        const selectedArr = Object.keys(params.selected).filter((item) => params.selected[item]);
        //点击之后所有未选中的图例数组
        const unSelectedArr = Object.keys(params.selected).filter((item) => !params.selected[item]);
        // 除了当前点击的图例，其他设为未选中
        selectedArr.forEach((item) => {
          if (item != params.name) this.chart.dispatchAction({ type: 'legendUnSelect', name: item });
        });
        //是否为点击已选中的的图例，操作：true：未选中图例变为已选中图例，false：未选中图例不变
        const clickSelect = !selectedArr.includes(params.name);
        unSelectedArr.forEach((item) => {
          if (clickSelect) this.chart.dispatchAction({ type: 'legendSelect', name: item });
        });
      }
      this.$emit('legendselectchanged', params);
    },
    setOptions(option) {
      this.clearChart();
      this.resizeHandler();
      if (this.chart) {
        this.chart.setOption(option);
      }
    },
    refresh() {
      // this.setOptions(this.chartOption)
      this.chart.setOption(this.chartOption);
    },
    reSetOptions(option) {
      this.chart.setOption(option);
    },
    clearChart() {
      this.chart && this.chart.clear();
    },
  },
};
</script>
